<template>
  <el-upload
      class="avatar-uploader"
      action="http://localhost:8999/us/api/user/upload/0db90cdc46af793258e2c70b146fc9f2/"
      list-type="picture-card"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :http-request="uploadSectionFile"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
  </el-upload>
</template>

<script lang="js">
import { UploadFilled, Plus } from '@element-plus/icons-vue'
import {ref} from "vue";
import {POST} from "../../api";
import {ElMessage} from "element-plus";

export default {
  name: "Upload",
  components: {
    UploadFilled,
    Plus
  },
  setup() {
    const imageUrl = ref("");

    const handleAvatarSuccess = (res, file) => {
      imageUrl.value = URL.createObjectURL(file.raw)
    }

    const uploadSectionFile = (params) => {
      const file = params.file
      const formData = new FormData()
      formData.set("file", file)
      formData.append("file", file);
      console.log(formData)
      POST(`/user/upload/${JSON.parse(localStorage.getItem("user")).userId}/`, formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }).then(res => {
        ElMessage.success("头像上传成功")
      }).catch(err => {
        ElMessage.error("头像上传失败")
      })
    }

    return {
      imageUrl,
      uploadSectionFile,
      handleAvatarSuccess
    }
  }
}

</script>

<style lang="scss" scoped>
</style>